# coding:utf-8

# @Title: ty_log.py
# @Package cdx_scan
# @Description: log information
# @author fuhaitao
# @version V1.0
# @Copyright: 2017 www.secsmarts.com Inc. All rights reserved.

import __main__
import logging.handlers
import os
# import ty_config as config
import socket
# from ty_ip_utils import get_internet_info
import datetime
import syslog

log_folder = '/var/log/messages'

module_name = os.path.basename(__main__.__file__)
if 'LOG_FILE_NAME' in os.environ.keys():
    module_name = module_name.replace(".py", "_" + os.environ['LOG_FILE_NAME'])

if not os.path.exists(log_folder):
    os.mkdir(log_folder)

# _, hostIPAddr, _, hostMac = get_internet_info()

logfile_path = os.path.join(log_folder, module_name + '.log')
formatter = logging.Formatter('%(process)d %(levelname)s: %(message)s')

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

# add file support
filehandler = logging.handlers.TimedRotatingFileHandler(logfile_path, 'D', 1, backupCount=10)
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

#address = ("172.20.10.9", 514)
address = ("192.168.1.67", 514)
#address = ("10.1.3.40", 515)
syslog_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host_name = socket.gethostname()

FACILITY = {
    'kern': 0, 'user': 1, 'mail': 2, 'daemon': 3,
    'auth': 4, 'syslog': 5, 'lpr': 6, 'news': 7,
    'uucp': 8, 'cron': 9, 'authpriv': 10, 'ftp': 11,
    'local0': 16, 'local1': 17, 'local2': 18, 'local3': 19,
    'local4': 20, 'local5': 21, 'local6': 22, 'local7': 23,
}

'''def syslog_format(message, level=syslog.LOG_NOTICE, facility=FACILITY['daemon']):
    return '<{0}>{1} {2} {3}: {4} {5} {6}'.format(level + facility * 8,
                                                    datetime.datetime.now().strftime("%b %d %H:%M:%S.%f"),
                                                    host_name, module_name, hostIPAddr, hostMac, message)
'''


def syslog_format(message, level=syslog.LOG_NOTICE, facility=FACILITY['daemon']):
    return '<{0}>{1} {2} {3}: {4} '.format(level + facility * 8,
                                           datetime.datetime.now().strftime("%b %d %H:%M:%S.%f"),
                                           host_name, module_name, message)


def info_ip_mac(strline, ip, mac):
    syslog_message = '<{0}>{1} {2} {3}: {4} {5} {6}'.format(syslog.LOG_NOTICE + FACILITY['daemon'] * 8,
                                                            datetime.datetime.now().strftime("%b %d %H:%M:%S.%f"),
                                                            host_name, module_name, ip, mac, strline)
    logger.info(syslog_message)
    send_to_syslog(syslog_message)


def info(strline, send2syslog=False):
    syslog_message = syslog_format(strline, level=syslog.LOG_INFO, facility=FACILITY['user']);
    logger.info(syslog_message)
    if send2syslog:
        send_to_syslog(syslog_message)


def error(strline, send2logstash=True):
    syslog_message = syslog_format("<TY_ERROR> " + strline, level=syslog.LOG_ERR, facility=FACILITY['user']);
    logger.error(syslog_message)
    if send2logstash:
        send_to_syslog(syslog_message)


def debug(strline):
    syslog_message = syslog_format(strline, level=syslog.LOG_DEBUG, facility=FACILITY['user']);
    logger.debug(syslog_message)


def warning(strline, send2logstash=False):
    syslog_message = syslog_format(strline, level=syslog.LOG_DEBUG, facility=FACILITY['user']);
    logger.warning(syslog_message)
    if send2logstash:
        send_to_syslog(syslog_message)


def send_to_syslog(syslog_message):
    try:
        syslog_socket.sendto(syslog_message, address)
        #syslog.syslog(syslog_message)
    except Exception as e:
        logging.error("send2syslog: {0}".format(e))
